import React, { useState } from 'react'
import { ArxivPaper } from '../../types/auth'
import { Button } from '../ui/Button'
import { Badge } from '../ui/Badge'
import { 
  Bookmark, 
  BookmarkCheck, 
  ExternalLink, 
  Calendar,
  User,
  Tag,
  Star
} from 'lucide-react'
import { cn } from '../../utils/cn'
import { formatDistanceToNow } from 'date-fns'

interface PaperCardProps {
  paper: ArxivPaper
  variant?: 'default' | 'compact' | 'detailed'
  showBookmark?: boolean
  showRating?: boolean
  onBookmark?: (paperId: string) => void
  onRate?: (paperId: string, rating: number) => void
  className?: string
}

export function PaperCard({ 
  paper, 
  variant = 'default',
  showBookmark = true,
  showRating = false,
  onBookmark,
  onRate,
  className 
}: PaperCardProps) {
  const [isBookmarked, setIsBookmarked] = useState(false)
  const [rating, setRating] = useState(0)
  const [isLoading, setIsLoading] = useState(false)

  const handleBookmark = async (e: React.MouseEvent) => {
    e.preventDefault()
    e.stopPropagation()
    
    setIsLoading(true)
    try {
      await onBookmark?.(paper.id)
      setIsBookmarked(!isBookmarked)
    } catch (error) {
      console.error('Error bookmarking paper:', error)
    } finally {
      setIsLoading(false)
    }
  }

  const handleRate = async (newRating: number) => {
    try {
      await onRate?.(paper.id, newRating)
      setRating(newRating)
    } catch (error) {
      console.error('Error rating paper:', error)
    }
  }

  const handleClick = () => {
    window.location.href = `/app/paper/${paper.arxiv_id}`
  }

  if (variant === 'compact') {
    return (
      <div 
        className={cn(
          "border border-gray-200 rounded-lg p-4 hover:shadow-md transition-shadow cursor-pointer bg-white",
          className
        )}
        onClick={handleClick}
      >
        <div className="flex items-start justify-between">
          <div className="flex-1 min-w-0 pr-4">
            <h3 className="font-medium text-gray-900 line-clamp-2 hover:text-blue-600 transition-colors">
              {paper.title}
            </h3>
            <p className="text-sm text-gray-600 mt-1">
              {paper.authors.slice(0, 3).join(', ')}
              {paper.authors.length > 3 && ` +${paper.authors.length - 3} more`}
            </p>
            <div className="flex items-center space-x-4 mt-2 text-xs text-gray-500">
              <span className="flex items-center">
                <Calendar className="h-3 w-3 mr-1" />
                {formatDistanceToNow(new Date(paper.published_date), { addSuffix: true })}
              </span>
              <span>arXiv:{paper.arxiv_id}</span>
            </div>
          </div>
          
          {showBookmark && (
            <Button
              variant="ghost"
              size="sm"
              onClick={handleBookmark}
              disabled={isLoading}
              className="flex-shrink-0"
            >
              {isBookmarked ? (
                <BookmarkCheck className="h-4 w-4 text-blue-600" />
              ) : (
                <Bookmark className="h-4 w-4" />
              )}
            </Button>
          )}
        </div>
      </div>
    )
  }

  return (
    <div 
      className={cn(
        "bg-white border border-gray-200 rounded-lg p-6 hover:shadow-lg transition-shadow cursor-pointer",
        className
      )}
      onClick={handleClick}
    >
      <div className="space-y-4">
        {/* Header */}
        <div className="flex items-start justify-between">
          <div className="flex-1">
            <h2 className="text-lg font-semibold text-gray-900 hover:text-blue-600 transition-colors line-clamp-2">
              {paper.title}
            </h2>
            <div className="flex items-center space-x-2 mt-2">
              <User className="h-4 w-4 text-gray-400" />
              <span className="text-sm text-gray-600">
                {paper.authors.slice(0, 3).join(', ')}
                {paper.authors.length > 3 && (
                  <span className="text-gray-500"> +{paper.authors.length - 3} more</span>
                )}
              </span>
            </div>
          </div>
          
          <div className="flex items-center space-x-2 ml-4">
            {showBookmark && (
              <Button
                variant="ghost"
                size="sm"
                onClick={handleBookmark}
                disabled={isLoading}
              >
                {isBookmarked ? (
                  <BookmarkCheck className="h-4 w-4 text-blue-600" />
                ) : (
                  <Bookmark className="h-4 w-4" />
                )}
              </Button>
            )}
            <Button
              variant="ghost"
              size="sm"
              onClick={(e) => {
                e.stopPropagation()
                window.open(paper.pdf_url, '_blank')
              }}
            >
              <ExternalLink className="h-4 w-4" />
            </Button>
          </div>
        </div>

        {/* Abstract */}
        {variant === 'detailed' && (
          <p className="text-gray-700 text-sm line-clamp-3">
            {paper.abstract}
          </p>
        )}

        {/* Categories and metadata */}
        <div className="flex items-center justify-between">
          <div className="flex items-center space-x-4">
            <div className="flex items-center space-x-2">
              <Tag className="h-3 w-3 text-gray-400" />
              <div className="flex flex-wrap gap-1">
                {paper.categories.slice(0, 3).map(category => (
                  <Badge key={category} variant="secondary" className="text-xs">
                    {category}
                  </Badge>
                ))}
                {paper.categories.length > 3 && (
                  <Badge variant="outline" className="text-xs">
                    +{paper.categories.length - 3}
                  </Badge>
                )}
              </div>
            </div>
          </div>
          
          <div className="flex items-center space-x-4 text-xs text-gray-500">
            <span className="flex items-center">
              <Calendar className="h-3 w-3 mr-1" />
              {formatDistanceToNow(new Date(paper.published_date), { addSuffix: true })}
            </span>
            <span>arXiv:{paper.arxiv_id}</span>
          </div>
        </div>

        {/* Rating */}
        {showRating && (
          <div className="flex items-center space-x-2 pt-2 border-t border-gray-100">
            <span className="text-sm text-gray-600">Rate this paper:</span>
            <div className="flex items-center space-x-1">
              {[1, 2, 3, 4, 5].map((star) => (
                <button
                  key={star}
                  onClick={(e) => {
                    e.stopPropagation()
                    handleRate(star)
                  }}
                  className="p-1 hover:bg-gray-100 rounded"
                >
                  <Star
                    className={cn(
                      "h-4 w-4 transition-colors",
                      star <= rating 
                        ? "text-yellow-400 fill-current" 
                        : "text-gray-300 hover:text-yellow-400"
                    )}
                  />
                </button>
              ))}
            </div>
          </div>
        )}
      </div>
    </div>
  )
}